package com.linghang.pc;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.seimicrawler.xpath.JXDocument;

import javax.lang.model.util.Elements;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Main {
    public static void main(String[] args) throws IOException {


        // 1. 打开浏览器>>>创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2. 输入网址,模拟发送请求，设置相关参数(例如可设置请求头，响应时间…)
        // (发起get请求，创建HttpGet对象)
        HttpGet httpGet1 = new HttpGet("http://whbsz.com.cn/Price.aspx?PageNo=1");
        // 3. 回车，使用HttpClient对象发起请求，返回响应|发送, 获取响应数据
        CloseableHttpResponse response1 = httpClient.execute(httpGet1);
        // 4. 解析响应，获取数据|获取html页面
        //通过状态码判断请求是否正常
        if (response1.getStatusLine().getStatusCode() == 200) {
            //获取响应体
            HttpEntity httpEntity1 = response1.getEntity();
            //解析响应体
            String content1 = EntityUtils.toString(httpEntity1, "utf8");
        }

        String html = EntityUtils.toString(response1.getEntity());
        File file = new File("src/main/resources/html/武汉白沙洲农产品.html");
        PrintStream ps = new PrintStream(new FileOutputStream(file));
        ps.println(html);

//        Elements tr1s = doc.selNOne("/body").asElement().select("tr.center");
//        String[] names = {"品名", "产地/规格", "最高价", "最低价", "平均价"};
//        for (Element tr1 : tr1s) {
//            String[] strings = tr1.text().split("\\s+");// 用空白字符分隔数据
//            StringBuilder productInfo = new StringBuilder();
//            for (int i = 0; i < 5; ++i) {
//                productInfo.append(names[i]).
//                        append(": ").append(strings[i]).append("\t");
//            }
//        }
//        System.out.println(productInfo);

//        String Html = EntityUtils.toString(res.getEntity());
//        JXDocument doc = JXDocument.create(Html);
//        List<JXNode> trs = doc.selN("//tr[contains(@class,'Center')]");
//        System.out.println(trs.size());


    }
}











